<template>
	<el-container>
		<div class="right-panel">
			<div class="right-panel-search" style="width: 100%; margin-top: 5px; margin-bottom: 5px">
				<!-- <div class="panel-search-box2">
					<el-select v-model="search.provs" placeholder="请选择省份" style="width: 180px; margin-left: 10px"
						filterable clearable @change="regionChange" @clear="clearSelect">
						<el-option v-for="item in provinceList" :key="item.provinceList" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div> -->
				<div class="panel-search-box2">
					<el-cascader @change="changeProv" v-model="province" :collapse-tags="true" max-collapse-tags="1"
						:show-all-levels="false" :options="options" :props="{ multiple: true }" clearable
						style="margin-left: 10px; width: 180px" placeholder="请选择省/市" />

				</div>
				<div class="panel-search-box2">
					<el-select v-model="search.prdName" placeholder="请选择品种" style="width: 180px; margin-left: 10px"
						filterable clearable>
						<el-option v-for="item in admMkMainBusinessTypes" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div>

				<div class="panel-search-box2" style="margin-left: 10px;">
					<el-input v-model="search.businessCustName" placeholder="请输入商道客户名称" style="width: 180px"
						clearable></el-input>
				</div>

				<div class="panel-search-box2" style="margin-left: 10px;">
					<el-input v-model="search.businessCustCode" placeholder="请输入商道客户编码" style="width: 180px"
						clearable></el-input>
				</div>
				<div class="panel-search-box2">
					<el-input v-model="search.distributorName" placeholder="请输入配送商名称"
						style="width: 180px; margin-left: 10px" clearable></el-input>

				</div>
				<div class="panel-search-box2">
					<el-input v-model="search.distributorCode" placeholder="请输入配送商编码"
						style="width: 180px; margin-left: 10px" clearable></el-input>

				</div>
				<div class="panel-search-box2" style="margin-left: 10px;">
					<el-input v-model="search.recordDownTerminalName" placeholder="请输入备案下游终端名称" style="width: 180px"
						clearable></el-input>
				</div>
				<div class="panel-search-box2">
					<el-input v-model="search.recordDownTerminalCode" placeholder="请输入备案下游终端编码"
						style="margin-left: 10px; width: 180px" clearable></el-input>
				</div>
				<div class="panel-search-box">
					<el-button type="primary" style="margin-left: 10px" @click="upsearch">查询</el-button>
					<el-button type="" @click="cleanSearch">清空</el-button>
				</div>

				<div style="margin-left: 300px;">
					<el-button type="primary" style="margin-left: 10px" @click="delRowData">批量删除</el-button>
					<!-- <el-button type="primary" style="margin-left: 10px" @click="inveDistribution(0)">覆盖导入</el-button> -->
					<el-button type="primary" style="margin-left: 10px"
						@click="centerDialogVisible = true">覆盖导入</el-button>
					<el-button type="primary" style="margin-left: 10px" @click="inveDistribution(1)">新增导入</el-button>
					<el-button type="primary" style="margin-left: 10px" @click="dialog = true">导出</el-button>
				</div>
			</div>
		</div>
		<el-header style="display: none"></el-header>
		<el-main class="nopadding">
			<scTable ref="table" border :apiObj="apiObj" :params="params" stripe remoteSort remoteFilter
				@selection-change="selectionChange">
				<!-- <el-table-column type="selection" width="50"></el-table-column> -->
				<el-table-column type="selection" :selectable="selectable" width="40" />
				<el-table-column label="备案日期" prop="recordDate" align="center" width="150"></el-table-column>
				<el-table-column label="操作人"  prop="operator" align="center" width="150"></el-table-column>
				<el-table-column label="片区责任人" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'areaManager'"
							v-model="scope.row.areaManager" placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'areaManager')">
							{{ scope.row.areaManager }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="省份" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'prov'" v-model="scope.row.prov"
							placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;" @dblclick="handleCellDblClick(scope.row.id, 'prov')">
							{{ scope.row.prov }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="城市" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'city'" v-model="scope.row.city"
							placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;" @dblclick="handleCellDblClick(scope.row.id, 'city')">
							{{ scope.row.city }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="品种" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'proName'" v-model="scope.row.proName"
							placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;" @dblclick="handleCellDblClick(scope.row.id, 'proName')">
							{{ scope.row.proName }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="商道客户名称" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'businessCustName'"
							v-model="scope.row.businessCustName" placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'businessCustName')">
							{{ scope.row.businessCustName }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="商道客户编码" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'businessCustCode'"
							v-model="scope.row.businessCustCode" placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'businessCustCode')">
							{{ scope.row.businessCustCode }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="所在城市配送商名称" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'distributorName'"
							v-model="scope.row.distributorName" placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'distributorName')">
							{{ scope.row.distributorName }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="配送商编码" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'distributorCode'"
							v-model="scope.row.distributorCode" placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'distributorCode')">
							{{ scope.row.distributorCode }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="备案下游终端名称" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'recordDownTerminalName'"
							v-model="scope.row.recordDownTerminalName" placeholder="请输入备注"
							@blur="handleInputBlur(scope.row)" @keyup.enter="handleInputBlur(scope.row)" ref="inputRef"
							style="width:100%">
						</el-input>

						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'recordDownTerminalName')">
							{{ scope.row.recordDownTerminalName }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="备案下游终端编码" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'recordDownTerminalCode'"
							v-model="scope.row.recordDownTerminalCode" placeholder="请输入备注"
							@blur="handleInputBlur(scope.row)" @keyup.enter="handleInputBlur(scope.row)" ref="inputRef"
							style="width:100%">
						</el-input>
						<div v-else style="min-height: 20px;"
							@dblclick="handleCellDblClick(scope.row.id, 'recordDownTerminalCode')">
							{{ scope.row.recordDownTerminalCode }}
						</div>

					</template>
				</el-table-column>

				<el-table-column label="备注" prop="remarks" align="center" width="150">
					<template #default="scope">
						<el-input v-if="doubleId == scope.row.id && doubleKey == 'remarks'" v-model="scope.row.remarks"
							placeholder="请输入备注" @blur="handleInputBlur(scope.row)"
							@keyup.enter="handleInputBlur(scope.row)" ref="inputRef" style="width:100%">
						</el-input>
						<div v-else style="min-height: 20px;" @dblclick="handleCellDblClick(scope.row.id, 'remarks')">
							{{ scope.row.remarks }}
						</div>
					</template>
				</el-table-column>


				<el-table-column label="操作" fixed="right" align="center" width="100">
					<template #default="scope">
						<el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row)">
							<template #reference>
								<el-button text type="primary" size="small">删除</el-button>
							</template>
						</el-popconfirm>
					</template>
				</el-table-column>
			</scTable>
		</el-main>


	</el-container>
	<scFileImport ref="scFileImport" :apiObj="importApi" :maxSize="30" hideButton @success="handleImportSuccess">
	</scFileImport>
	<!-- 导出 -->
	<scFileExport ref="scFileExport" :apiObj="deriveExcel" :post="true" :data="search" fileName="数据导出" hideButton>
	</scFileExport>

	<el-dialog v-model="centerDialogVisible" title="是否进入覆盖导入？" width="500" align-center>
		<span>注意：覆盖导入，会将原有数据全部覆盖，即原有数据将被删除。<br>请谨慎操作！</span>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="centerDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="inveDistribution(0), centerDialogVisible = false">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
	<el-dialog v-model="doloadVisible" title="导入结果" width="900" align-center>
		成功条数：{{ doloadData.successNum }}
		失败条数：{{ doloadData.failNum }}
		<H3 style="margin-top:20px">导入失败明细</H3>
		<el-table :data="JSON.parse(doloadData.failRecords)" style="width: 100%">
			<el-table-column prop="provs" label="省份" />
			<el-table-column prop="cities" label="城市" />
			<el-table-column prop="prdName" label="品种" />
			<el-table-column prop="businessCustName" label="商道客户名称" />
			<el-table-column prop="addbusinessCustCoderess" label="商道客户编码" />
			<el-table-column prop="distributorName" label="所在城市配送商名称" />
			<el-table-column prop="distributorCode" label="配送商编码" />
			<el-table-column prop="recordDownTerminalName" label="备案下游终端名称" />
			<el-table-column prop="recordDownTerminalCode" label="备案下游终端编码" />
			<el-table-column prop="remarks" label="备注" />
		</el-table>

	</el-dialog>

	<el-drawer v-model="dialog" title="导出" :size="400" direction="rtl" append-to-body destroy-on-close>
		<el-main style="padding: 0 20px 20px 20px">
			<el-form label-width="100px" label-position="left" style="margin: 10px 0 20px 0">
				<el-form-item label="文件名">
					<el-input v-model="formData.fileName" placeholder="请输入文件名" />
				</el-form-item>
				<el-form-item label="文件类型">
					<el-select v-model="formData.fileType" placeholder="请选择文件类型">
						<el-option label="xlsx" value="xlsx" />
						<el-option label="xls" value="xls" />
					</el-select>
				</el-form-item>
			</el-form>
			<el-button type="primary" size="large" icon="el-icon-download" style="width: 100%" @click="exportDetail">下
				载</el-button>

		</el-main>
	</el-drawer>


</template>

<script>
import { ElLoading } from 'element-plus'
export default {
	name: 'customerList',
	data() {
		return {
			search: {},
			apiObj: this.$API.customerCenter.filingWhiteList.recordWhitelist,
			params: {},
			cityList: [], //市列表
			provinceList: [], //省份列表
			admMkMainBusinessTypes: [],//品种
			delData: [],
			importApi: this.$API.log.upload,
			deriveExcel: this.$API.customerCenter.filingWhiteList.download,
			deriveExcelIndex: '',
			centerDialogVisible: false,
			doubleId: '',
			doubleKey: '',
			options: [],
			selectedProvinces: [],
			selectedCities: [],
			province: [],
			doloadVisible: false,
			doloadData: {},
			dialog: false,
			formData: {
				fileType:'xlsx'
			}
		}
	},
	watch: {

	},

	mounted() {
		this.getSelectData()
	},
	created() {

	},
	methods: {
		changeProv(value) {
			// 清空存储
			this.search.provs = [];
			this.search.cities = [];

			value.forEach((path) => {
				const [provinceValue, cityValue] = path;
				const province = this.options.find((item) => item.value === provinceValue);
				const city = province?.children?.find((item) => item.value === cityValue);

				if (city) {
					this.search.cities.push(city.label);
				}

				if (province) {
					const isProvinceExist = this.search.provs.some(
						(item) => item === province.label
					);
					if (!isProvinceExist) {
						this.search.provs.push(province.label);
					}
				}
			});


		},

		handleCellDblClick(id, name) {
			// row.isEditing = true;
			this.doubleId = id
			this.doubleKey = name
			// this.$nextTick(() => {
			// 	this.$refs.inputRef.focus();
			// });
		},
		async handleInputBlur(row) {
			this.doubleId = ''
			this.doubleKey = ''
			// 这里可以添加保存数据的逻辑
			let res = await this.$API.customerCenter.filingWhiteList.updateRecordWhitelist.post({ data: row })//接口获取blob数据
			this.$message.success('修改成功')
		},

		async exportDetail(e) {
			let res = await this.$API.customerCenter.filingWhiteList.download.post({ data: this.search })//接口获取blob数据
			const url = window.URL.createObjectURL(new Blob([res]));
			const link = document.createElement('a');
			link.style.display = 'none';
			link.href = url;
			const fileName = this.formData.fileName + '.' + this.formData.fileType;
			link.setAttribute('download', fileName);
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			this.dialog=false
		},
		async handleImportSuccess(res, close) {
			const loading = ElLoading.service({
				lock: true,
				text: '正在导入，请稍后..',
			})

			if (this.deriveExcelIndex == 1) {
				// 新增导入
				let filePath = await this.$API.customerCenter.filingWhiteList.importWhitelist.post({ data: { filePath: res.data } })
				this.doloadData = filePath.data
			} else if (this.deriveExcelIndex == 0) {
				// 覆盖导入
				let filePath = await this.$API.customerCenter.filingWhiteList.coverImportWhitelist.post({ data: { filePath: res.data } })
				this.doloadData = filePath.data
				this.doloadData = filePath.data
			}
			loading.close()

			this.doloadVisible = true
			close()
			this.$refs.table.upData()
		},
		inveDistribution(index) {
			this.deriveExcelIndex = index
			this.$refs.scFileImport.open()
		},
		table_del(e) {
			this.$API.customerCenter.filingWhiteList.deleteRecordWhitelist.post({
				data: {
					ids: [e.id]
				}
			}).then((res) => {
				this.upsearch()
				this.$message.success('删除成功')
			})
		},
		delRowData() {
			if (this.delData.length == 0) {
				this.$message.warning('请至少选择一条数据！')
				return
			}
			this.$API.customerCenter.filingWhiteList.deleteRecordWhitelist.post({
				data: {
					ids: this.delData
				}
			}).then((res) => {
				this.upsearch()
				this.$message.success('删除成功')
			})
		},
		selectionChange(arr) {
			this.delData = []
			arr.forEach((e) => {
				this.delData.push(e.id)
			})

		},
		getSelectData() {
			this.provinceList = []
			this.$API.customerCenter.filingWhiteList.getChinaTree.get().then((res) => {

				console.log('省市数据', res.data);
				// res.data.forEach((e) => {
				// 	this.provinceList.push({
				// 		value: e.province,
				// 		label: e.province
				// 	})

				// })
				this.options = res.data.map((province) => ({
					label: province.province,
					value: province.code,
					children: province.cities.map((city) => ({
						label: city.name,
						value: city.name,
					}))
				}))

			})

			this.$API.customerCenter.filingWhiteList.admMkMainBusinessTypes.get().then((res) => {
				this.admMkMainBusinessTypes = []
				res.data.forEach((e) => {
					this.admMkMainBusinessTypes.push({
						value: e.prdNameDms,
						label: e.prdNameDms
					})
				})

			})
		},
		upsearch() {
			this.$refs.table.upData(this.search)
		},
		cleanSearch() {
			this.search = {}
			this.$refs.table.reload(this.search)
		},
		doubleClick(e) {
			this.doubleId = e
		},
	}
}
</script>

<style>
.header-btn-item {
	display: flex;
}

.panel-search-box2 {
	margin: 10px 0;
}
</style>
